const express = require('express')
const app = express()
const cors = require('cors')
const router = require('./router/index')

//解析 json
app.use(express.json())
//解析 application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))

app.use('/public', express.static('./public'))
app.use('/img', express.static('./coverImg'))
app.use(cors())
app.use((req, res, next) => {
    res.sendErr = (err, status = 1) => {
        //如果传进来的错误是对象就取err.message 如果是字符串就直接err
        err = err instanceof Error ? err.message : err
        //响应
        res.send({ status: status, message: err })
    }
    next()
})
//路由
app.use('/api', router)

//全局错误
app.use((err, req, res, next) => {
    console.log(err.name);
    console.log(err);
    if (err) res.sendErr(err)
})

app.listen('3006', () => {
    console.log('服务器启动 访问http:127.0.0.1:3006');
})

